package com.zxl.live.tools.image;

import java.util.LinkedList;

/**
 * Created by Administrator on 2017/6/14.
 */

public class ImageExecutorService {

    private int nThreads;

    private int mRunThread;

    private LinkedList<ImageRunnable> mList;

    public ImageExecutorService(int nThreads) {
        this.nThreads = nThreads;
        mList = new LinkedList<>();
    }

    public void execute(ImageRunnable command) {
        synchronized (this) {
            if (mList.contains(command)) {
                if (mList.remove(command)) {
                    mList.addFirst(command);
                }
            } else {
                mList.addFirst(command);
            }
        }

        if (nThreads >= mRunThread) {
            mRunThread++;
            new Thread("thread" + mRunThread) {

                @Override
                public void run() {
                    while (true) {
                        ImageRunnable imageRunnable;
                        synchronized (ImageExecutorService.this) {
                            if (mList.isEmpty()) {
                                break;
                            }
                            imageRunnable = mList.removeFirst();
                        }
                        try {
                            imageRunnable.run();
                        } catch (Throwable e) {
                            e.printStackTrace();
                        }
                    }
                    mRunThread--;
                }
            }.start();
        }
    }

    public static class ImageRunnable implements Runnable {

        private String tags;

        public ImageRunnable(String tags) {
            this.tags = tags;
        }

        @Override
        public void run() {

        }

        @Override
        public boolean equals(Object o) {
            if (ImageRunnable.class.isInstance(o)) {
                return tags.equals(((ImageRunnable) o).tags);
            }
            return super.equals(o);
        }
    }

}
